import {queryIndex, subscribePoetryService} from '../services/poet.js'

export default {

  namespace: 'index',

  state: {
    subscribeStatus: -1, // -1 表示不现实 1表示成功
    subscribeMsg: '恭喜订阅成功!',
    face: [
      'https://s3.mogucdn.com/mlcdn/c45406/180404_5fi9b1l2c3b0bg71ddcj66dd4abbg_1280x854.jpg',
      'http://s3.mogucdn.com/mlcdn/c45406/180405_1i3c2ch5bif7j845j2al2fl021hlj_599x360.jpg',
      'https://s17.mogucdn.com/mlcdn/c45406/180405_2g460jj9k6hel275b41ij1f5gjekd_690x170.jpg',
    ],
    title: '首页!',
    poetryList: [
      {
        id: 40663,
        title: '菩萨蛮',
        author: '刘学箕',
        dynasty: '宋词',
        pic: 'https://s3.mogucdn.com/mlcdn/c45406/180404_5fi9b1l2c3b0bg71ddcj66dd4abbg_1280x854.jpg',
        content: '昨日杏花春满树。\n' +
        '今晨雨过香填路。\n' +
        '零落软胭脂。\n' +
        '湿红无力飞。\n' +
        '转头春易去。\n' +
        '春色归何处。\n' +
        '待密与春期。\n' +
        '春归人也归。',
      }
    ]
  },

  subscriptions: {
    setup({dispatch, history}) {  // eslint-disable-line
      dispatch({
        type: 'fetch',
      })
    },
  },

  effects: {
    * fetch({payload}, {call, put}) {  // eslint-disable-line
      const res = yield call(queryIndex);
      yield put({type: 'save', payload: res.data.result});
    },


    // 订阅服务，传入邮箱地址和昵称
    * subscribe({payload}, {call, put}) {
      console.log("开始订阅啦: ", payload);

      const res = yield call(subscribePoetryService, payload);
      console.log("res: ", res);
      let msg = '恭喜您订阅成功';
      if (res.data.status && res.data.status.code !== 200) { // 成功
        msg = '订阅失败: ' + res.data.status.msg;
      }

      yield put({
        type: 'updateSubStatus', payload: {
          subscribeMsg: msg,
          subscribeStatus: 1,
        }
      });
    },

    * hideToast({payload}, {call, put}) {
      yield put({
        type: 'updateSubStatus',
        payload: {
          subscribeMsg: '关闭弹窗',
          subscribeStatus: -1,
        },
      })
    }
  },

  reducers: {
    /**
     * 首页查询成功，然后将后端返回的诗词写入list中,供前端渲染
     * @param state
     * @param apps
     * @returns {{apps: *, poetryList: Uint8Array | any[] | Int32Array | Uint16Array | Uint32Array | Float64Array | *}}
     */
    save(state, {payload: apps}) {
      const list = apps.map(app => {
          return {
            id: app.id,
            title: app.title,
            author: app.author,
            content: app.content,
            dynasty: app.dynasty,
          }
        }
      );
      // console.log(JSON.stringify(list));
      return {...state, apps, poetryList: list};
    },

    /**
     * 订阅之后，用于显示订阅成功与否的弹窗信息, 因为没有使用第三方的toast库，所以自己写了一个特别水的弹窗，
     * 需要更新props来关闭和显示弹窗，并传回对应的提示信息
     * @param state
     * @param apps
     * @returns {{apps: *, subscribeStatus: number|*, subscribeMsg: string|string|string|*}}
     */
    updateSubStatus(state, {payload: apps}) {
      return {...state, apps, subscribeStatus: apps.subscribeStatus, subscribeMsg: apps.subscribeMsg};
    },
  },

};
